package com.fanchuan.uzx.ui.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;


public class ImageTools {
	
	
	public static String md5(String str) {
		try {
			// Create MD5 Hash
			MessageDigest digest = java.security.MessageDigest
					.getInstance("MD5");
			digest.update(str.getBytes());
			byte messageDigest[] = digest.digest();

			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++)
				hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static String getCacheFilePath(String url) {
		return md5(url);
	}
	public static File downloadFileCache(String filePath,Context mContext){
		
		File mFile = mContext.getDir("files", Context.MODE_PRIVATE);
		File file = new File(mFile.getAbsolutePath() +"/"+getCacheFilePath(filePath));
		Log.d("filecache", file.getAbsolutePath());
		if(file.exists())
			return file;
		return null;
	}
	
	public static File downloadFileWeb(String url, Context mContext){
		
		try {
			URL u = new URL(url);
			File mFile = mContext.getDir("files", Context.MODE_PRIVATE);
			
			File file = new File(mFile.getAbsolutePath() +"/"+getCacheFilePath(url));
			Log.d("downloadFile", file.getAbsolutePath());
			URLConnection  connection = u.openConnection();
			InputStream in = connection.getInputStream();
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			int length = 0;
			byte []buffer = new byte[1024];
			while((length=in.read(buffer))!= -1){
				fileOutputStream.write(buffer, 0, length);
			}
			fileOutputStream.flush();
			fileOutputStream.close();
			return file;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Bitmap getBitmapFromFile(File file){
		Log.d("file", file.getAbsolutePath());
		Bitmap bmp =  BitmapFactory.decodeFile(file.getAbsolutePath());
		return bmp;
	}
}
